package com.lmm.lcbusiness.lcbusiness.pages.richtxt.main;

import com.lmm.dresswisdom.lmmframe.retrofit.AppCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.FileUtils;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcbusiness.lcbusiness.ReturnInfo;
import com.lmm.lcbusiness.lcbusiness.cominterface.UploadCallBack;
import com.lmm.lcbusiness.lcbusiness.config.AppInfoAction;
import com.lmm.lcbusiness.lcbusiness.config.ConfigValue;
import com.lmm.lcbusiness.lcbusiness.config.DataSafeUtil;
import com.lmm.lcbusiness.lcbusiness.pages.CommonAction;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;

public class RichTxtPresent implements RichTxtContract.IPresent {

    RichTxtContract.IView mView;
    CommonAction commonAction;

    public RichTxtPresent(RichTxtContract.IView mView) {
        this.mView = mView;
        commonAction = AppClient.getRetrofit(ConfigValue.apiUrl).create(CommonAction.class);
    }

    @Override
    public void getTokenAction() {
        Map<String, String> params = AppInfoAction.getParams();
        AppClient.request(commonAction.getToken(DataSafeUtil.EncodeMAP(params)), new AppCallBack<ReturnInfo>() {
            @Override
            public void onSuccess(ReturnInfo returnInfo) {
                if (returnInfo.isSuccess()) {
                    Map<String, Object> mapObj = (Map<String, Object>) returnInfo.getData();
                    String tok = (String) mapObj.get("token");
                    mView.setQNToken(tok);
                } else {
                    LogUtils.write(returnInfo.getMessage());
                }
            }

            @Override
            public void onFailure(String s) {
                ToastUtils.showToastShort(s);
            }

            @Override
            public void onFinish() {

            }
        });
    }


    @Override
    public void uploadImgAction(String token, String filetag, File mfile, final UploadCallBack uploadCallBack) {
        UploadManager uploadManager = new UploadManager();
        final String filename = FileUtils.getDateFileName(mfile.getName(), filetag);
        uploadManager.put(mfile, filename, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    ToastUtils.showToastShort("上传成功");
                    uploadCallBack.uploadFinish(filename);
                } else {
                    ToastUtils.showToastShort("图片上传失败");
                }
            }
        }, null);
    }
}